import { make } from "../../utils/dom"
import styles from "./index.module.less"
import { uploadFreeFileFn } from "@/utils/file"
import { IconLoader } from "@codexteam/icons"

interface MediaControlsConfig {
	placeholder?: string
	renderButtonText: string
}
class ControlUploadDomBase {
	wrapper: HTMLElement
	api: any
	config: MediaControlsConfig

	constructor(wrapper: HTMLElement, api: any, config: MediaControlsConfig) {
		this.wrapper = wrapper
		this.api = api
		this.config = config
	}
	render() {
		const controlBox = make("div", styles.controlBox)
		const saveBtn = make("div", styles.saveBtn, { innerText: this.config.renderButtonText })
		const uploadBtn = make("div", styles.uploadBtn, { innerText: "上传" })
		const ipt = make("input", styles.ipt, {
			placeholder: this.config.placeholder || "请输入",
		})
		controlBox.append(ipt, uploadBtn, saveBtn)
		this.wrapper.append(controlBox)
		this.api.listeners.on(
			uploadBtn,
			"click",
			() => {
				uploadFreeFileFn((error, data, upLoading) => {
					if (upLoading === "start") {
						uploadBtn.innerHTML = `${IconLoader} 上传中...`
					}
					if (error) {
						uploadBtn.innerHTML = `${IconLoader} 上传失败`
					} else {
						if (!data) return
						this.update(data.url)
					}
				})
			},
			false
		)
		this.api.listeners.on(
			saveBtn,
			"click",
			() => {
				this.update((ipt as HTMLInputElement).value)
			},
			false
		)
	}

	update(val: string) {
		const curIdx = this.api.blocks.getCurrentBlockIndex()
		const curBlock = this.api.blocks.getBlockByIndex(curIdx)
		this.api.blocks.update(curBlock.id, {
			url: val,
		})
	}
}
export default ControlUploadDomBase

